﻿using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Architecture;
using CommunityToolkit.Mvvm.ComponentModel;
using System;
using System.Diagnostics;
// *** 确保 using Autodesk.Revit.DB; 存在 ***

namespace RevitProject.SpaceManager.ViewModel.RoomViewModelPart
{
    /// <summary>
    /// Room 的 ViewModel 包装类，手动实现属性。
    /// (诊断步骤3：恢复单位转换逻辑)
    /// </summary>
    public partial class RoomViewModel : ObservableObject // 保持 partial
    {
        private readonly Room _room;
        public Room RevitRoom => _room;

        // --- 手动实现属性 ---
        private string _roomNumber;
        public string RoomNumber { get => _roomNumber; set => SetProperty(ref _roomNumber, value); }

        private string _roomName;
        public string RoomName { get => _roomName; set => SetProperty(ref _roomName, value); }

        private string _formattedArea;
        public string FormattedArea { get => _formattedArea; set => SetProperty(ref _formattedArea, value); }

        private string _levelName;
        public string LevelName { get => _levelName; set => SetProperty(ref _levelName, value); }

        // *** 标高属性，将显示转换后的毫米值 ***
        private string _levelElevation;
        public string LevelElevation { get => _levelElevation; set => SetProperty(ref _levelElevation, value); }
        // ************************************

        private string _categoryName;
        public string CategoryName { get => _categoryName; set => SetProperty(ref _categoryName, value); }
        // --------------------

        public RoomViewModel(Room room)
        {
            // 1. 基础检查
            if (room == null) throw new ArgumentNullException(nameof(room));
            if (!room.IsValidObject) throw new ArgumentException("传入的 Room 对象无效。", nameof(room));
            if (room.Document == null) throw new ArgumentException("传入的 Room 对象没有有效的 Document 引用。", nameof(room));
            _room = room;

            // --- 初始化临时变量 ---
            string tempRoomNumber = "错误"; string tempRoomName = "错误"; string tempFormattedArea = "错误";
            string tempLevelName = "错误"; string tempLevelElevation = "错误"; string tempCategoryName = "错误";

            // 2. 获取基本属性
            try { tempRoomNumber = _room.Number ?? "无编号"; } catch (Exception ex) { Debug.WriteLine($"获取房间 {_room.Id} 编号时出错: {ex.ToString()}"); }
            try { tempRoomName = _room.Name ?? "无名称"; } catch (Exception ex) { Debug.WriteLine($"获取房间 {_room.Id} 名称时出错: {ex.ToString()}"); }

            // 3. 获取并格式化面积
            try { const double sqFeetToSqMeters = 0.092903; Parameter areaParam = _room.get_Parameter(BuiltInParameter.ROOM_AREA); if (areaParam != null && areaParam.HasValue) { double areaInternal = areaParam.AsDouble(); double areaSqMeters = areaInternal * sqFeetToSqMeters; tempFormattedArea = $"{areaSqMeters:N2}"; } else { tempFormattedArea = "---"; } }
            catch (Exception ex) { Debug.WriteLine($"获取房间 {_room.Id} 面积时出错: {ex.ToString()}"); }

            // 4. *** 获取楼层名称和转换后的标高值 ***
            tempLevelName = "未知楼层"; // 默认值
            tempLevelElevation = "---";   // 默认值
            try
            {
                if (_room.LevelId != null && _room.LevelId != ElementId.InvalidElementId)
                {
                    if (_room.Document != null && _room.Document.IsValidObject)
                    {
                        Level level = _room.Document.GetElement(_room.LevelId) as Level;
                        if (level != null && level.IsValidObject)
                        {
                            tempLevelName = level.Name ?? "未知名称"; // 获取楼层名称

                            // --- 取消注释单位转换部分 ---
                            try
                            {
                                double elevationInternal = level.Elevation; // 获取标高值 (英尺)

                                // ****** 请根据您的 Revit 版本，取消注释下面两行中的【一行】 ******

                                // 方案 A: Revit 2021 及更高版本 (使用 UnitTypeId)
                                double elevationMM = UnitUtils.ConvertFromInternalUnits(elevationInternal, UnitTypeId.Millimeters);

                                // 方案 B: Revit 2020 及更早版本 (使用 DisplayUnitType)
                                // double elevationMM = UnitUtils.ConvertFromInternalUnits(elevationInternal, DisplayUnitType.DUT_MILLIMETERS);

                                // ***************************************************************

                                tempLevelElevation = $"{elevationMM:F0}"; // 格式化为毫米整数
                                Debug.WriteLine($"房间 {_room.Id} 转换后标高 (mm): {tempLevelElevation}");
                            }
                            catch (Exception unitEx) // 捕获单位转换可能发生的错误
                            {
                                Debug.WriteLine($"转换房间 {_room.Id} 标高单位时出错: {unitEx.ToString()}");
                                tempLevelElevation = "转换错误";
                            }
                            // -----------------------------
                        }
                    }
                    else { Debug.WriteLine($"房间 {_room.Id} 的 Document 无效，无法获取 Level。"); }
                }
            }
            catch (Exception ex) { Debug.WriteLine($"获取房间 {_room.Id} 的楼层信息时出错: {ex.ToString()}"); }
            // *********************************

            // 5. 获取空间类别
            const string categoryParamName = "空间类别"; tempCategoryName = "其他类";
            try { Parameter param = _room.LookupParameter(categoryParamName); if (param != null && param.HasValue) { string paramValue = param.AsString(); if (!string.IsNullOrWhiteSpace(paramValue)) { tempCategoryName = paramValue; } } }
            catch (Exception ex) { Debug.WriteLine($"获取房间 {_room.Id} 的 '{categoryParamName}' 参数时出错: {ex.ToString()}"); }

            // --- 最后一次性赋值给公共属性 ---
            RoomNumber = tempRoomNumber; RoomName = tempRoomName; FormattedArea = tempFormattedArea;
            LevelName = tempLevelName; LevelElevation = tempLevelElevation; // 赋值转换后的标高字符串
            CategoryName = tempCategoryName;
        }
        


    }
}